package swordoffer.offer12;

public class BackTraceSolution {
    public static boolean exist(char[][] board, String word) {
        if (board.length == 0 || board[0].length == 0) {
            return false;
        }
        boolean[][] visited = new boolean[board.length][board[0].length];
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (dfs(board, word, i, j, 0, visited)) {
                    return true;
                }
            }
        }
        return false;
    }
    public static boolean dfs(char[][] board, String word, int i, int j, int index, boolean[][] visited) {
        if (index == word.length()) {
            return true;
        }
        if (i >= board.length || i < 0 || j >= board[0].length || j < 0 || board[i][j] != word.charAt(index)) {
            return false;
        }
        if (!visited[i][j]) {
            visited[i][j] = true;
            boolean res = dfs(board, word, i + 1, j, index + 1, visited)
                    || dfs(board, word, i - 1, j, index + 1, visited)
                    || dfs(board, word, i, j + 1, index + 1, visited)
                    || dfs(board, word, i, j - 1, index + 1, visited);
            visited[i][j] = false;
            return res;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
        char[][] board = new char[][] {{'a','a'}};
        String word = "aaa";
        exist(board, word);
    }
}
